import json
from flask import Blueprint, request, session
from flask_cors import CORS

from blueprints.utils import (
    response_error,
    response_success,
    remove_invalid_subscriptions,
    remove_invalid_config,
    is_valid_email,
)
from services.user import (
    is_user_exists,
    create_user,
    get_user,
    update_user,
)

from services.email import send_code_email, generate_code, verify_code

user_bp = Blueprint("user", __name__, url_prefix="/user")

CORS(
    user_bp,
    resources={
        r"/*": {
            "origins": ["http://localhost:5173"],
            "methods": ["GET", "POST", "PUT", "DELETE"],
            "supports_credentials": True,
        }
    },
)


@user_bp.route("/code", methods=["POST"])
def send_code():
    """
    发送验证码接口

    测试地址：http://127.0.0.1:5000/user/code
    """
    email = request.json.get("email")
    if not email or not is_valid_email(email):
        return response_error("邮箱不合法")

    # 生成验证码并发送邮件
    code = generate_code(email)
    send_code_email(code, email)

    return response_success("验证码已发送，请查收邮件")


@user_bp.route("/login", methods=["POST"])
def login():
    """
    用户登录接口

    测试地址：http://127.0.0.1:5000/user/login
    """
    email = request.json.get("email")
    code = request.json.get("code")

    if not email or not code:
        return response_error("邮箱和验证码不能为空")

    # 验证验证码
    if not verify_code(email, code):
        return response_error("验证码错误或已过期")

    # 检查用户是否存在
    if not is_user_exists(email):
        # 如果用户不存在，则创建新用户
        create_user(email)

    # 获取用户信息
    user = get_user(email)

    session["email"] = user.email
    return response_success(user.to_dict())


@user_bp.route("/logout", methods=["POST"])
def logout():
    """
    用户登出接口

    测试地址：http://127.0.0.1:5000/user/logout
    """
    session.clear()
    return response_success("登出成功")


@user_bp.route("/info", methods=["GET"])
def get_user_info():
    """
    获取用户信息接口

    测试地址：http://127.0.0.1:5000/user/info
    """
    email = session.get("email")
    if not email:
        return response_error("未登录"), 401
    user = get_user(email)
    return response_success(user.to_dict())


@user_bp.route("/subscribe", methods=["PUT"])
def subscribe():
    """
    订阅接口

    测试地址：http://127.0.0.1:5000/user/subscribe
    """
    email = session.get("email")
    if not email:
        return response_error("未登录"), 401
    subscribe_list = request.json.get("subscribe_list", [])

    # 更新用户订阅列表
    update_user(
        email, subscribed_hotspots=remove_invalid_subscriptions(subscribe_list)
    )
    
    user = get_user(email)

    return response_success({ "subscribe_list": user.subscribed_hotspots })


@user_bp.route("/update", methods=["PUT"])
def update_list_display():
    """
    更新用户配置

    测试地址：http://127.0.0.1:5000/user/update
    """
    email = session.get("email")
    if not email:
        return response_error("未登录"), 401
    
    user = get_user(email)
    config = remove_invalid_config(request.json.get("config", {}))
    new_config = user.config.copy()
    for key, value in config.items():
        new_config[key] = value
    update_user(email, config=new_config)

    user = get_user(email)
    return response_success({"config": user.config})
